<template>
  <!-- 对话框配置项: 关闭时销毁, 可拖拽, 居中-->
  <el-dialog
    v-model="dialogs.user.manage"
    title="用户信息修改"
    destroy-on-close
    draggable
    center
  >
    <el-table :data="gridData">
      <el-table-column property="id" label="ID" width="50" />
      <el-table-column property="user_name" label="用户名" width="100" />
      <el-table-column property="user_password" label="密码" />
      <el-table-column property="user_type" label="角色" sortable width="120"
        ><template #default="scope2">
          <el-tag
            v-if="scope2.row.user_type == 2"
            type="danger"
            effect="dark"
            size="small"
          >
            管理员
          </el-tag>
          <el-tag
            v-else-if="scope2.row.user_type == 1"
            type="warning"
            effect="dark"
            size="small"
          >
            交管部门
          </el-tag>
          <el-tag v-else type="" effect="dark" size="small"> 普通用户 </el-tag>
        </template>
      </el-table-column>
      <el-table-column property="user_status" label="登录" sortable>
        <template #default="scope3">
          <el-tag
            v-if="scope3.row.user_status != 0"
            type="success"
            effect="dark"
            size="small"
          >
            在线
          </el-tag>
          <el-tag v-else type="info" effect="dark" size="small">
            离线
          </el-tag></template
        ></el-table-column
      >
      <el-table-column property="user_truname" label="姓名" />
      <el-table-column property="user_phone" label="手机号" width="120" />
      <el-table-column label="信息管理" width="140" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :total="pager.total"
      :page-size="pager.pageSize"
      @current-change="handleCurrentChange"
    />
  </el-dialog>
  <el-dialog
    v-model="centerDialogVisible"
    title="修改信息"
    center
    width="450px"
  >
    <el-form
      status-icon
      :model="formRes"
      :rules="rulesRes"
      ref="formResr"
      :label-position="labelPosition"
      label-width="45px"
    >
      <el-form-item prop="name">
        <span>用户账号</span>
        <el-input
          maxlength="6"
          show-word-limit
          v-model="formRes.name"
        ></el-input>
      </el-form-item>
      <el-form-item prop="psd">
        <span>用户密码</span>
        <el-input
          type="password"
          show-password
          v-model="formRes.psd"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <span>用户类型</span>
        <!-- <el-input v-model="formRes.type"></el-input> -->
        <!-- <el-select v-model="formRes.type" placeholder="Select">
          <el-option
            v-for="item in user_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
          </el-option>
        </el-select> -->

        <el-radio-group v-model="formRes.type">
          <el-radio label="0" size="large">用户</el-radio>
          <el-radio label="1" size="large">交管</el-radio>
          <el-radio label="2" size="large">管理</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <span>用户状态</span>
        <el-radio-group v-model="formRes.status">
          <el-radio :label="0" size="large">离线</el-radio>
          <el-radio :label="1" size="large">在线</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="truname">
        <span>真实姓名</span>
        <el-input v-model="formRes.truname"></el-input>
      </el-form-item>
      <el-form-item prop="phone">
        <span>联系方式</span>
        <el-input
          maxlength="11"
          show-word-limit
          v-model="formRes.phone"
          oninput="value=value.replace(/[^\d]/g,'')"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消修改</el-button>
        <el-button type="primary" @click="handleChange"> 确认修改 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useDialogsStore } from '@/stores/dialogs' // 使用pinia
import { useUserStore } from '@/stores/user'
import userApi from '@/apis/user.js'
const labelPosition = ref('right')
const { dialogs } = useDialogsStore()
const centerDialogVisible = ref(false)
const { user } = useUserStore()
const item = ref({})
const gridData = ref([])
const token = localStorage.getItem('token')
const pager = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0,
})
const user_type = [
  {
    value: '0',
    label: '普通用户',
  },
  {
    value: '1',
    label: '交管部门',
  },
  {
    value: '2',
    label: '管理员',
  },
]
const user_status = [
  {
    value: '0',
    label: '未登录',
  },
  {
    value: '1',
    label: '登录',
  },
]
const onEditRow = ref(null)

onMounted(() => {
  getGridData()
})

// 获取用户数据
const getGridData = async () => {
  dialogs.user.manage = true
  const params = { page: pager.pageNum, num: pager.pageSize }
  const res = await userApi.getAll(params)
  gridData.value = res.result.data
  pager.total = res.result.total
}

// 分页
const handleCurrentChange = (current) => {
  pager.pageNum = current
  getGridData()
}
const formRes = reactive({
  name: '',
  psd: '',
  type: '',
  status: '',
  truname: '',
  phone: '',
})
// if (formRes.type == 0) {
//   item.label = '普通用户'
// } else if (formRes.type == 1) {
//   item.label = '交管部门'
// } else {
//   item.label = '管理员'
// }
// 表单校验规则
const rulesRes = {
  name: [
    { required: true, trigger: 'blur' },
    { min: 2, max: 6, message: '用户名长度在2~10个字符', trigger: 'blur' },
  ],
  psd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度在6~10个字符', trigger: 'blur' },
  ],
  // type: [
  //   { required: true, trigger: 'blur' },
  //   { message: '类型不能为空', trigger: 'blur' },
  // ],
  status: [
    { required: true, trigger: 'blur' },
    { max: 1, message: '类型不能为空', trigger: 'blur' },
  ],
  truname: [
    { required: true, message: '真实姓名不能为空', trigger: 'blur' },
    { min: 2, max: 5, message: '用户名长度在2~5个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    { min: 6, max: 11, message: '用户名长度在6~11个字符', trigger: 'blur' },
  ],
}
// 定义响应式数据
const formResr = ref(null)
// 点击编辑，传当前行数据，请求接口打开弹框
const handleEdit = (index, row) => {
  userApi.getById(row.id).then((res) => {
    // console.log(res.result[0], 2222)
    centerDialogVisible.value = true
    // if (token) {
    //   user.status = 1
    // }
    // user.value = res.result[0]
    const {
      id,
      user_name: name,
      user_type: type,
      user_password: psd,
      user_status: status,
      user_truname: truname,
      user_phone: phone,
    } = res.result[0] || {}
    Object.assign(formRes, { name, type, status, psd, truname, phone, id })
    // formRes.status = 1
    // Object.assign(formRes, { name, status, psd, truname, phone, id })
    // console.log(formRes, { name, type, status, psd, truname, phone, id }, 123)
  })
}
const handleChange = () => {
  formResr.value.validate((valid) => {
    // console.log(valid)
    if (!valid) {
      return false
    }
    // console.log('验证通过')
    const params = {
      user_name: formRes.name,
      user_password: formRes.psd,
      user_type: formRes.type,
      user_status: formRes.status,
      user_truname: formRes.truname,
      user_phone: formRes.phone,
    }
    userApi
      .edit(formRes.id, params)
      .then((res) => {
        console.log(res)
        if (res.code == '0') {
          // alert(res.message)
          // closable.value = false
          // formRef.value = ''
          ElMessage.success('修改成功')
          getGridData()
          // const targetRowIndex = gridData.value.findIndex(
          //   (item) => item.id == formRes.id
          // )
          // gridData.value[targetRowIndex] = {
          //   ...params,
          //   id: formRes.id,
          // }
        }
      })
      .catch((err) => {
        console.log(err)
      })
  })
  centerDialogVisible.value = false
}
// 删除用户
const handleDelete = (index, row) => {
  console.log(index, row)
  userApi.delById(row.id).then((res) => {
    console.log(res)
    row.user_status = 0
  })
}
</script>
<style scoped>
span {
  margin-right: 15px;
}
.el-input {
  width: 200px;
  margin-left: 5px;
}
</style>
